import {
	toast,
	showLoading,
	hideLoading,
	navigateTo
} from "."
import useUserStore from "@/store/user"

const options = {
	header: {
		'content-type': 'application/json'
	},
	noToken: false,
	showMessage: false,
	method: 'post',
	loading: false,
	backAll: false
}


const request = (url, config) => {

	config = {
		...options,
		...config
	}
	console.log("config-->", config)
	// config.header = {
	// 	'content-type': 'application/json'
	// }

	if (config.loading) {
		showLoading(config.loadText || '加载中...')
	}

	if (!config.noToken) {
		const userStore = useUserStore();
		console.log("userStore-->", userStore)
		// const user = userStore.userInfo

		// if (!user) {
		// 	toast("登录失效", "error")
		// 	navigateTo("/pages/login/index")
		// 	return
		// }

		const token = userStore.token;
		console.log("token-->", token)
		if (token) {
			config.header = {
				"Authorization": `Bearer ${token}`,
				...config.header
			}
		} else {
			toast("登录失效", "error")
			navigateTo("/pages/login/index")
			return
		}
	}



	return new Promise((resolve, reject) => {
		uni.request({
			url: `http://123.162.182.213:22541/${url}`,
			...config,
			success: (res) => {
				console.log(res)
				const {
					code,
					msg,
					data
				} = res.data
				console.log("code0", code, data, msg, code == 200)
				if (res.statusCode == 404) {
					toast('接口无效', "error")
					return
				}

				if (code == 200) {
					console.log("config.showMessage-->", config.showMessage)
					if (config.showMessage) toast(msg)
					if (config.backAll) resolve(res.data)
					else resolve(data)
				} else if (code == 401) {
					toast('登录失效', "error")
					navigateTo("/pages/login/index")
					return
				} else {
					toast(msg, "error")
					reject(res)
				}
			},
			fail: (err) => {
				console.log(err)
				reject(err)
			},
			complete: () => {
				if (config.loading) {
					hideLoading()
				}
			}
		})
	})
}

export default request;